package Network

import (
	"SQL/db"
	"net/http"
)

/*
URL: /addUser
/addUser? account=18826054758&password=123456
*/

type result struct {
	UserID string
}

func register(w http.ResponseWriter, req *http.Request) (code int, msg string, obj interface{}) {
	code = Success

	account := req.FormValue("account")
	msg, code = checkArgs("account", account)
	if code != Success {
		return
	}

	password := req.FormValue("password")
	msg, code = checkArgs("password", password)
	if code != Success {
		return
	}
	nickname := account
	code, msg, obj = AddUserToDB(password, account, nickname)
	return
}

func AddUserToDB(password string, account string, nickname string) (code int, msg string, Result interface{}) {
	//插入objects ->返回 id ->插入users ->完成
	DB := db.Open()
	defer db.Close(DB)
	tx, err := DB.Begin()
	if err != nil {
		code = errBeginTx
		msg = err.Error()
		return
	}

	defer func() {
		if code != Success {
			err := tx.Rollback()
			if err != nil {
				code = errEndTx
				msg = err.Error()
			}
		}
	}()

	var sql string
	sql = "select * from users where account = $1"
	stmt, rows, err := db.TxQuery(tx, sql, account)
	defer stmt.Close()
	defer rows.Close()
	if err != nil {
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	if rows.Next() {
		code = errExistSameAccount
		msg = mExistSameAccount
		return
	}
	rows.Close()
	sql = "insert into objects(nickname,isUser) values($1,true) returning id"
	stmt, rows, err = db.TxQuery(tx, sql, nickname)
	if err != nil {
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	var userID string
	if !rows.Next() {
		code = errDBQueryFailed
		msg = "no rows"
		return
	}
	err = rows.Scan(&userID)
	if err != nil {
		code = errRowsScan
		msg = err.Error()
		return
	}
	rows.Close()
	sql = "insert into users(id,account,password) values($1,$2,$3)"
	var objs []interface{}
	objs = append(objs, userID, account, password)
	err = db.TxExec(tx, sql, objs...)
	if err != nil {
		code = errDBExecFailed
		msg = err.Error()
		return
	}
	err = tx.Commit()
	if err != nil {
		code = errEndTx
		msg = err.Error()
		return
	}
	res := &result{UserID: userID}
	return Success, "", res
}
